(function ($) {
    var page = "news-flash";
    layui.use(['element', 'form', 'layer', 'laytpl', 'laydate'], function () {
        var model = $(".news-flash-content");
        var layer = layui.layer;
        var form = layui.form;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;

        laydate.render({
            elem: '.range-input'
            , type: 'datetime'
            , range: true
        });
        form.render();

        form.verify({
            integer: function (value, item) {
                if (value) {
                    try {
                        if (parseInt(value) != value) {
                            return "请输入整数";
                        }
                    } catch (error) {
                        return "请输入整数";
                    }
                }
            },
            positiveInteger: function (value, item) {//正整数
                if (value) {
                    try {
                        if (parseInt(value) != value || value <= 0) {
                            return "请输入正整数";
                        }
                    } catch (error) {
                        return "请输入正整数";
                    }
                }
            }
        });
        //是否有任务在执行
        var processing = false;

        var table = $(".news-flash-table").table({
            columns: [
                {
                    "name": "title",
                    "display": "快讯标题",
                    "width": "15%"
                },
                /*{
                    "name": "candy",
                    "display": "糖果数"
                },*/
                {
                    "name": "content",
                    "display": "内容",
                    "width": "40%"
                },
                {
                    "name": "supportAmount",
                    "display": "利好"
                },
                {
                    "name": "boycottAmount",
                    "display": "利空"
                },
                {
                    "name": "emergency",
                    "display": "紧急程度",
                    "render": function (rowData) {
                        var emergencyContent = "一般";
                        if (rowData.emergency == "01") {
                            emergencyContent = "一般";
                        } else if (rowData.emergency == "02") {
                            emergencyContent = "紧急";
                        }
                        return emergencyContent;
                    }
                },
                {
                    "name": "createTime",
                    "display": "创建时间"
                },
                {
                    "name": "status",
                    "display": "状态",
                    "render": function (rowData) {
                        if (rowData.status == "01") {
                            return "<font color='#00bfff'>上线</font>";
                        } else {
                            return "<font color='gray'>下线</font>";
                        }
                    }
                },
                /*{
                    "name": "expireTime",
                    "display": "过期时间",
                    "render": function (rowData) {
                        console.log(rowData);
                        rowData.expireTimeInHour = (rowData.expireTime / 3600).toFixed(0);
                        return rowData.expireTimeInHour + "小时";
                    }
                },*/
                {
                    "display": "操作",
                    render: function (rowData) {
                        var ret = "<div class='opt-btn-group'>";
                        if (rowData.status == "01") {
                            ret += "<span class='update-status-item'><i class=\"layui-icon\">&#xe857;</i><font color='red'>下线</font></span>";
                        } else {
                            ret += "<span class='update-status-item'><i class=\"layui-icon\">&#xe857;</i><font color='#00bfff'>上线</font></span>";
                        }
                        ret += "<span class='edit-item'><i class=\"layui-icon\">&#xe642;</i>编辑</span>" +
                            // "<span class='delete-item'><i class=\"layui-icon\">&#xe640;</i>删除</span>" +
                            "</div>";
                        return ret;
                    }
                }
            ],
            url: "/hycj/news",
            showTitle: false,
            formatData: function (data) {
                console.log(data.datas)
                return data.datas;
            },
            params: {
                channelId: 7
            }
        });

        //编辑对话框
        model.on("click", ".edit-item", function (e) {
            var rowData = table.getRowData($(e.target).closest("tr"));
            $.getJsonData("/hycj/news/" + rowData.id).done(function (data) {
                //data.datas.expireTimeInHour = (data.datas.expireTime / 3600).toFixed(0);
                if (data.datas.image) {
                    data.datas.imageArray = data.datas.image.split(",");
                } else {
                    data.datas.imageArray = [];
                }
                laytpl($("#news-flashForm").html()).render({
                    model: "updateNewsFlashForm",
                    data: data.datas
                }, function (content) {
                    layer.open({
                        type: 1,
                        title: "更新快讯",
                        content: content,
                        area: "600px",
                        maxHeight: app.clientHeight() - 50,
                        success: function () {
                            form.render();
                            $("[name='tag']").tagsinput({
                                tagClass: 'big',
                                confirmKeys: [44, 65292, 9, 32]
                            });
                            // laydate.render({
                            //     elem: '[name="expireTime"]'
                            //     , type: 'datetime'
                            //     , format: 'yyyy-MM-dd HH:mm'
                            //     , min: 0
                            //     , max: 1
                            // })
                        }
                    });
                });
            });
        });

        //创建对话框
        model.on("click", ".create-item", function (e) {
            laytpl($("#news-flashForm").html()).render({
                model: "addNewsFlashForm",
                data: {}
            }, function (content) {
                layer.open({
                    type: 1,
                    title: "创建快讯",
                    content: content,
                    area: "600px",
                    maxHeight: app.clientHeight() - 50,
                    success: function () {
                        form.render();
                        $("[name='tag']").tagsinput({
                            tagClass: 'big',
                            confirmKeys: [44, 65292, 9, 32]
                        });
                        // laydate.render({
                        //     elem: '[name="expireTime"]'
                        //     , type: 'datetime'
                        //     , format: 'yyyy-MM-dd HH:mm'
                        //     , min: 0
                        //     , max: 1
                        // })
                    }
                });
            });
        });

        //删除对话框
        model.on("click", ".delete-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            layer.msg('您确认删除<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {
                    $.getJsonData("/hycj/news"
                        , {id: selectedData.id}
                        , {type: "Delete"})
                        .done(function () {
                            layer.msg("删除完成");
                            table.refresh();
                        }).fail(function () {
                        layer.msg("删除失败, 请稍后重试!");
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        //上下线对话框
        model.on("click", ".update-status-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            var tipInfo = "下线";
            //下线改上线
            if (selectedData.status == "00") {
                tipInfo = "上线";
                selectedData.status = "01";
            } else {
                //上线改下线
                selectedData.status = "00";
            }

            //作者保存时，使用author字段
            layer.msg('您确认' + tipInfo + '<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {

                    $.getJsonData("/hycj/news", selectedData, {type: "Put"}).done(function (data) {
                        if (data.code != "200") {
                            layer.msg('操作失败', {icon: 2});
                        } else {
                            app.showSuccess();
                            table.refresh();
                        }
                        processing = false;
                    }).fail(function () {
                        processing = false;
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        //搜索
        form.on('submit(searchNewsFlashForm)', function (data) {
            if (!data.form) {
                return false
            }
            table.refresh(data.field);
            return false;
        });

        //新增
        form.on('submit(addNewsFlashForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            processing = true;
            //data.field.expireTime = data.field.expireTime * 3600;

            //将附图表单内容组装成逗号相隔的字符串
            var contentCombine = "";
            $("[name='cover']", data.form).each(function (index, e) {
                contentCombine += "," + $(e).val();
            });

            if (contentCombine) {
                data.field.image = contentCombine.substring(1);
            }
            $.getJsonData("/hycj/news", data.field, {type: "Post"}).done(function (data) {
                if (data.code == '500') {
                    layer.msg(data.message, {icon: 2});
                } else {
                    layer.closeAll();
                    layer.msg('操作成功', {icon: 6});
                    table.refresh();
                }
                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });

        //更新
        form.on('submit(updateNewsFlashForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            processing = true;
            //data.field.expireTime = data.field.expireTime * 3600;

            //将附图表单内容组装成逗号相隔的字符串
            var contentCombine = "";
            $("[name='cover']", data.form).each(function (index, e) {
                contentCombine += "," + $(e).val();
            });

            if (contentCombine) {
                data.field.image = contentCombine.substring(1);
            }
            $.getJsonData("/hycj/news", data.field, {type: "Put"}).done(function (data) {
                if (data.code == '500') {
                    layer.msg(data.message, {icon: 2});
                } else {
                    app.showSuccess();
                    table.refresh();
                }
                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });


        form.verify({
            expireTime: function (value, item) {
                var expireTimeIntVal;
                try {
                    expireTimeIntVal = parseInt(value)
                } catch (error) {
                    return "过期时间只能为数字";
                }
                if (expireTimeIntVal < 6 || expireTimeIntVal >= 24) {
                    return "过期时间只能为6（包括）到24（不包括）小时";
                }
            }
        });

        app.bindPageEvents(page, function () {
            //增加海报表单项
            $(document).on("click", ".news-flash-form .add-cover-btn", function (e) {
                if ($(".cover").length >= 3) {
                    layer.msg("附图不能超过3张", {icon: 2});
                    return false;
                }
                var $addBtn = $(e.currentTarget);
                moon.uploader({
                    //上传成功的回调，回调数据为文件上传的路径。格式如下：[{path:xxx},{path:xxx}]
                    callback: function (uploadRet) {
                        $(uploadRet).each(function (index, uploadItem) {
                            $addBtn.before(" <div class=\"cover\">\n" +
                                "<i class=\"layui-icon remove-cover\">&#x1007;</i>" +
                                "                        <input type=\"hidden\" name=\"cover\" required lay-verify=\"required\"\n" +
                                "                               autocomplete=\"off\" value=\"" + uploadItem.path + "\"\n" +
                                "                               class=\"layui-input show-uploader\">\n" +
                                "                        <img src=\"" + uploadItem.path + "\" class=\"cover-item\"/>\n" +
                                "                    </div>");
                            if ($(".cover").length >= 3) {
                                $(".add-cover-btn").hide();
                            }
                        });
                    }
                });
            });

            //移除海报表单项
            $(document).on("click", ".news-flash-form .remove-cover", function (e) {
                var $coverDiv = $(e.target).closest(".cover");
                $coverDiv.remove();
                $(".add-cover-btn").show();
            });
        });
    });
})(jQuery);